package cn.yunhe.controller;

import cn.yunhe.entity.Department;
import cn.yunhe.entity.User;
import cn.yunhe.service.impl.UserServiceImpl;
import com.github.pagehelper.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Resource
    private UserServiceImpl userService;

    @RequestMapping("addUser")
    public String addUser(User user, Department department){
        user.setDepartment(department);
        Timestamp creatTime = new Timestamp(new Date().getTime());
        user.setCreateTime(creatTime);
        int count = userService.addUser(user);
        if(count > 0){
            return "success";
        }else {
            return "failed";
        }
    }

    @RequestMapping("getAllUserByPage")
    public Map getAllUserByPage(int pageSize, int currPage, User user, Department department){
        user.setDepartment(department);
        Map<String,Object>map = new HashMap<>();
        map.put("pageSize", pageSize);
        map.put("currPage", currPage);
        map.put("user", user);
        Page page = userService.getUserByPage(map);
        map.put("page", page);
        map.put("totalPage", page.getPages());
        return map;
    }

    @RequestMapping("editPwd")
    public ModelAndView editPwd(int userId){
        ModelAndView mv = new ModelAndView("edit-password");
        mv.addObject("userId", userId);
        return mv;
    }

    @RequestMapping("updUserPwd")
    public int updUserPwd(User user){
        return userService.updUserPwd(user);
    }

    @RequestMapping("editInfo")
    public ModelAndView editInfo(HttpServletRequest request, int userId){
        ModelAndView mv = new ModelAndView("editUserInfo");
        User user = userService.getUserById(userId);
        user.setUserId(userId);
        request.setAttribute("user", user);
        return mv;
    }

    @RequestMapping("doEdit")
    public int doEdit(User user, Department department){
        user.setDepartment(department);
        return userService.updUserInfo(user);
    }

    @RequestMapping("doDisable")
    public int doDisable(int userId){
        return userService.updUserIsDisable(userId);
    }

    public UserServiceImpl getUserService() {
        return userService;
    }

    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }
}
